package com.pro01.backend.service;

import com.pro01.backend.dto.PromotionActiveDTO;
import com.pro01.backend.dto.UserPromotionRecordDTO;
import com.pro01.backend.mapper.Promotion2Mapper;
import com.pro01.backend.mapper.TorrentMapper;
import com.pro01.backend.mapper.UserPromotion2Mapper;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Promotion2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Promotion2Service {

    @Autowired
    private Promotion2Mapper promotion2Mapper;

    @Autowired
    private TorrentMapper torrentMapper;

    @Autowired
    private UserPromotion2Mapper userPromotion2Mapper;

    // 管理员设置促销
    public boolean createPromotion(Promotion2 promotion) {
        //return promotion2Mapper.insertPromotion(promotion) > 0;
        boolean inserted = promotion2Mapper.insertPromotion(promotion) > 0;

        if (inserted) {
            // 同步更新种子表
            torrentMapper.updatePromotionInfo(
                    promotion.getTorrentId(),
                    promotion.getPromotionType(),
                    promotion.getEndTime()
            );
        }

        return inserted;
    }

    // 管理员取消促销
    public boolean cancelPromotion(Long torrentId) {
        boolean deleted = promotion2Mapper.deletePromotionByTorrentId(torrentId) > 0;
        if (deleted) {
            torrentMapper.resetPromotionInfo(torrentId);
        }
        return deleted;
    }

    // 用户查看当前有效促销
    public PageResult<PromotionActiveDTO> getActivePromotionsPaged(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<PromotionActiveDTO> list = promotion2Mapper.getActivePromotions(offset, pageSize);
        int total = promotion2Mapper.countActivePromotions();
        return new PageResult<>(total, list);
    }

    // 用户查看自己领取的促销奖励
    public PageResult<UserPromotionRecordDTO> getUserPromotionsPaged(Long userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<UserPromotionRecordDTO> list = userPromotion2Mapper.getUserPromotionRecords(userId, offset, pageSize);
        int total = userPromotion2Mapper.countUserPromotionRecords(userId);
        return new PageResult<>(total, list);
    }


}

